<?php
require_once 'pages/TMSFrontPage.inc';
require_once 'security/captcha.inc';
require_once 'util/TFormPersistance.inc';

class TMSFrontRegisterPage extends TMSFrontPage {
/**
 * @var TMSClientModel
 */	
	protected $_ioc_client_model_;
	
	protected $_array_hide_properties_ = array();
	
	private $_formdata_;
	
	public function __construct($path, $filename, TIntrinsicPageService $service){
		parent::__construct($path, $filename, $service);
		$this->_formdata_ = new TFormPersistance($this); 
	}
	
	public function Properties(){
		$item = $this->ClientModel->GetDummyItem();	
		foreach ($this->_formdata_->FormData() as $nm=>$value)
			$item->$nm = $value;
/*
 * @todo refactor this copypaste 
 */		
		return array_udiff($item->Properties(),$this->_array_hide_properties_,create_function('$a,$b','return strcmp(($a instanceof IPropertyMeta)?$a->Name():(string)$a,($b instanceof IPropertyMeta)?$b->Name():(string)$b);'));
	}
	
	public function http_Register(){
		$props = $this->ClientModel->ClassProperties();
		$this->_formdata_->SaveProperties($props,$form);
		
		$this->checkCaptcha($this->request->captcha);
		
		if (!$this->request->pwd)
			throw new TExposableException('Пароль не может быть пустым!');
			
		if ($this->request->pwd != $this->request->pwd2)	
			throw new TExposableException('Подтверждение пароля не совпадает с паролем!');
		
		foreach ($props as $p){
			if ($p->Required() && !isset($form[$p->Name()]))
				throw new TExposableException('Поле "'._i($p->Name()).'" не может быть пустым!');
		}
		$form['Active'] = true;				
		if ($item = $this->ClientModel->CreateItem($form)){
			$this->service->Acl->SetPassword($item->ItemId(),$this->request->pwd);
			$this->service->Acl->Login($item->Login,$this->request->pwd);
		}
		$this->_formdata_->Clear();
		$this->Application()->Redirect($this->Application()->Url());
	}
}
